package com.c.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**认证失败处理器
 * @author wangxiangli
 * @create 2022-12-25-21:41
 */
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        Map map = new HashMap();
        String errorMsg = exception.getMessage();

        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            errorMsg = "密码输入错误，请重新输入!";
        } else if (exception instanceof DisabledException) {
            errorMsg = "账户被禁用，登录失败，请联系管理员!";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            errorMsg = "用户不存在，请重新登陆!";
        } else {
            errorMsg = "登录失败!";
        }

        map.put("success", false);
        map.put("errorMsg", errorMsg);

        String str = objectMapper.writeValueAsString(map);

        response.setContentType("text/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(str);
        out.flush();
        out.close();
    }
}
